﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;
using System.Data;

namespace Technoera.Common.Interop.OleDb
{
    public class XlsImportTask<T> where T : new()
    {
        private IList<IImportMapping> _mappings;
        public IList<IImportMapping> Mappings
        {
            get
            {
                if (_mappings == null)
                    _mappings = new Collection<IImportMapping>();

                return _mappings;
            }
        }

        public IList<T> Import(string xlsFullFileName, ExcelVersion excelVersion, string sheetName)
        {
            Collection<T> result = new Collection<T>();
            using (XlsReader xls = new XlsReader(xlsFullFileName, excelVersion))
            {
                IDataReader dataReader = xls.GetDataReader(sheetName);
                while (dataReader.Read())
                {
                    if (IsEmptyRow(dataReader)) continue;

                    T item = new T();
                    foreach (IImportMapping mapping in Mappings)
                    {
                        mapping.SetPropertyValue(dataReader, item);
                    }
                    result.Add(item);
                }
            }
            return result;
        }

        private static bool IsEmptyRow(IDataReader dataReader)
        {
            for (Int32 i = 0; i < dataReader.FieldCount; i++)
            {
                if (dataReader[i] != null && !(dataReader[i] is System.DBNull))
                {
                    if (dataReader[i] is string && ((string)dataReader[i]).Length == 0)
                    {
                        continue;
                    }
                    return false;
                }
            }
            return true;
        }

    }
}
